<template>
    <div class="container">
        <div ref="docxContentRef" id="demoDocContainer"/>
    </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {ElLoading, ElMessage} from "element-plus";
import {blobToFile} from "@/common/utils/GlobalUtils";
//导入PDFObject
import PDFObject from 'pdfobject';

const router = useRouter();
let getFileUrlKey = router.currentRoute.value.params.fileUrlKey;

/**
 * 通过fileKey获取文件流预览docx文档
 * @param templateUrlKey
 */
const docxContentRef = ref(null);
const getWord = (fileUrlKey, callback,err_callback) => {
    reserveInvestmentProjectLibraryApi.getPlanWord({templateUrlKey: fileUrlKey}).then(res => {
        if (res) {
            let blob = new Blob([res], {
                type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
            });

            // 将blob转换为file
            let file = blobToFile(blob,new Date().getTime(),'application/pdf');
            // 将file转换为dataUrl
            let dataUrl = URL.createObjectURL(file);
            PDFObject.embed(dataUrl, '#demoDocContainer', { width: '100%',heigth: '100%' });
            setTimeout(()=>{
                URL.revokeObjectURL(dataUrl);
            },1000);
            if (callback) callback();
        }
        if(res.code !==undefined && res.code === '200'){
            if (err_callback) err_callback();
        }
    });
}


onMounted(() => {
    if (getFileUrlKey !== '') {
        let fileUrlKey = getFileUrlKey.replaceAll("@", "/");
        const loading = ElLoading.service({
            lock: true,
            text: 'loading...',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
            getWord(fileUrlKey, () => {
                loading.close();
            },()=>{
                ElMessage.error('加载失败!');
                loading.close();
            });
        }, 1000);
    }
});
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}

#demoDocContainer{
    height: 100vh !important;
}
</style>